import fetch from 'isomorphic-fetch';
import { ErrorObj, ErrorTypeEnum } from 'shared/errors';
import { showLoadingbar } from 'shared/actions/loadingBar';
import { reportError } from '../actions/error';
import * as ContentTypeEnum from './consts/ContentTypeEnum';
import toQueryString from '../utils/toQueryString';
import processHeaders from './processHeaders';
import {showLoading, hideLoading } from './promiseCounter';
import store from '../../store';

import { notification } from 'antd';
import { local } from '../utils/func';

export default class Request {
  static instance = new Request;

  constructor() {
    ['get', 'post', 'put', 'patch', 'delete', 'head'].forEach((method) => {

      this[method] = (path, data) => {
        let token = local.getSession('token');
        let manager_id = local.getSession('manager_id');
        if(token && manager_id){
          data.token = token;
          data.manager_id = manager_id;
        }
        let headers = {};
        let body;
        if (data) {
          if (data.body) {
            headers = data.headers || {};
            body = data.body;
          } else {
            body = data;
          }
        }

        const fetchConfig = {
          method,
          headers: processHeaders(method, headers),
          // credentials: 'include',
        };


        let params = body;
        if (fetchConfig.headers['Content-Type'] !== ContentTypeEnum.JSON) {
          params = toQueryString(body);
        }

        if (method !== 'get' && method !== 'delete') {
          fetchConfig.body = params;
        } else {
          const paramsString = params ? `${params}&` : '';
          path = `${path}${path.indexOf('?') !== -1 ? '&' : '?'}${paramsString}ui_random=${new Date().getTime()}`;
        }

        showLoading();
        return fetch(path, fetchConfig)
          .then((httpResponse = {}) => {
            const { status, statusText = '', ok } = httpResponse;
            hideLoading();
            if (ok) {
              return httpResponse.json();
            } else {
              throw new ErrorObj(ErrorTypeEnum.HTTP, statusText, {
                code: status,
                url: path,
                response: httpResponse
              });
            }
          })
          .then((JSONResponse) => {
            if (JSONResponse.code === 401) {
              location.hash = '#/SignIn';
            }
            if(JSONResponse.code != 200){
              // throw new ErrorObj(ErrorTypeEnum.APP, JSONResponse.msg);
              notification.error({
                message:JSONResponse.code,
                description:JSONResponse.msg
              })
            }
            // console.log(JSONResponse)
            return JSONResponse;
          })
          .catch((error) => {
            store.dispatch(showLoadingbar(false));
            store.dispatch(reportError(error));
            throw (error);
          });
      };
    });
  }
}